window.onload = function(){
	$('#loading-mask').fadeOut();
}

var onlyOpenTitle  ="首页";//不允许关闭的标签的标题
var _menus         = '';//菜单json
var _shortcutmenus ='';//快捷菜单json


$(function(){
	InitLeftMenu(); //初始化左侧菜单
	tabClose();
	tabCloseEven();
	InitShortCut(); //初始化 快捷菜单 面板
	var bLock = $.cookie('ipoms_lock');
	
	if ( bLock =='true'){
		lockSystem();
	}

/* 选择TAB时刷新内容
	$('#tabs').tabs({
        onSelect: function (title) {
            var currTab = $('#tabs').tabs('getTab', title);
            var iframe = $(currTab.panel('options').content);

			var src = iframe.attr('src');
			if(src)
				$('#tabs').tabs('update', { tab: currTab, options: { content: createFrame(src)} });

        }
    });
*/
})

/*
var _menus = {
            "menus": [{
                "menuid": "1",
                "icon": "icon-sys",
                "menuname": "标注管理",
                "menus": [{
                    "menuid": "12",
                    "menuname": "添加标注",
                    "icon": "icon-add",
                    "url": "http://hxling.cnblogs.com",
                    "child": [{
                        "menuid": "140",
                        "menuname": "角色管理 3",
                        "icon": "icon-role",
                        "url": "demo2.html"
                    },
                        {
                            "menuid": "150",
                            "menuname": "权限设置 3",
                            "icon": "icon-set",
                            "url": "demo.html"
                        }]
                },
                    {
                        "menuid": "13",
                        "menuname": "标注类别管理",
                        "icon": "icon-users",
                        "url": "demo2.html",
                        "child": [{
                            "menuid": "141",
                            "menuname": "角色管理 3",
                            "icon": "icon-role",
                            "url": "demo.html"
                        },
                            {
                                "menuid": "151",
                                "menuname": "权限设置 3",
                                "icon": "icon-set",
                                "url": "demo1.html"
                            }]
                    },
                    {
                        "menuid": "14",
                        "menuname": "标注统计",
                        "icon": "icon-role",
                        "url": "demo2.html",
                        "child": [{
                            "menuid": "142",
                            "menuname": "角色管理 3",
                            "icon": "icon-role",
                            "url": "demo2.html"
                        },
                            {
                                "menuid": "152",
                                "menuname": "权限设置 3",
                                "icon": "icon-set",
                                "url": "demo.html"
                            }]
                    },
                    {
                        "menuid": "15",
                        "menuname": "权限设置",
                        "icon": "icon-set",
                        "url": "demo.html",
                        "child": [{
                            "menuid": "143",
                            "menuname": "角色管理 3",
                            "icon": "icon-role",
                            "url": "demo2.html"
                        },
                            {
                                "menuid": "153",
                                "menuname": "权限设置 3",
                                "icon": "icon-set",
                                "url": "demo.html"
                            }]
                    },
                    {
                        "menuid": "16",
                        "menuname": "系统日志",
                        "icon": "icon-log",
                        "url": "demo1.html",
                        "child": [{
                            "menuid": "144",
                            "menuname": "角色管理 3",
                            "icon": "icon-role",
                            "url": "demo2.html"
                        },
                            {
                                "menuid": "154",
                                "menuname": "权限设置 3",
                                "icon": "icon-set",
                                "url": "demo.html"
                            }]
                    }]
            },
                {
                    "menuid": "8",
                    "icon": "icon-sys",
                    "menuname": "地理要素管理",
                    "menus": [{
                        "menuid": "21",
                        "menuname": "员工列表",
                        "icon": "icon-nav",
                        "url": "demo.html"
                    },
                        {
                            "menuid": "22",
                            "menuname": "视频监控",
                            "icon": "icon-nav",
                            "url": "demo1.html",
                            "child": [{
                                "menuid": "221",
                                "menuname": "员工列表 3",
                                "icon": "icon-nav",
                                "url": "demo.html"
                            },
                                {
                                    "menuid": "222",
                                    "menuname": "视频监控 3",
                                    "icon": "icon-nav",
                                    "url": "demo1.html"
                                }]
                        }]
                },
                {
                    "menuid": "56",
                    "icon": "icon-sys",
                    "menuname": "数据管理",
                    "menus": [{
                        "menuid": "31",
                        "menuname": "添加部门",
                        "icon": "icon-nav",
                        "url": "demo1.html"
                    },
                        {
                            "menuid": "321",
                            "menuname": "部门列表",
                            "icon": "icon-nav",
                            "url": "demo2.html",
                            "child": [{
                                "menuid": "311",
                                "menuname": "添加部门 4",
                                "icon": "icon-nav",
                                "url": "demo1.html"
                            },
                                {
                                    "menuid": "312",
                                    "menuname": "部门列表 4",
                                    "icon": "icon-nav",
                                    "url": "demo2.html"
                                }]
                        }]
                }]
        };
*/
/*
 * 
 *getUserMenu返回JSON格式： 如上
 * 
 */
//初始化左侧
function InitLeftMenu() {
	$("#nav").empty();
	$("#nav").accordion({animate:false,fit:true,border:false});
	var selectedPanelname = '';
    
    $.ajax({
        type: "GET",
        url : "getUserMenu",
        data: '',
        dataType: 'json',
        async: false,
        success:function(reponse){
            _menus = reponse;
        },
        error: function(xhr, type){
        	showError('获取菜单出错',"网络异常,无法获取用户菜单");
        }
    });
    $.each(_menus.menus, function(i, n) {
		var menulist ='';
		menulist +='<ul class="navlist">';
        $.each(n.menus, function(j, o) {
        	if (o.menuname =='-'){
        		menulist += '<div class="menu-sep"></div>';
        	}else{
        		if (o.favflag=='1'){ //如果标志1已收藏
        			menulist += '<li><div ><a ref="'+o.menuid+'" href="#" rel="' + o.url + '" ><img align="baseline" src="'+o.icon+'"><span class="nav">' + o.menuname + '</span></a> <img class="fav" type="removefav" id="fav'+o.menuid+'" ref="'+o.menuid+'" src="yhui/images/menu/star.png" align="right" rel="'+ o.menuname +'" title="取消收藏->'+o.menuname+'"></div> ';
        		}else{
        			menulist += '<li><div ><a ref="'+o.menuid+'" href="#" rel="' + o.url + '" ><img align="baseline" src="'+o.icon+'"><span class="nav">' + o.menuname + '</span></a> <img class="fav" type="addfav" id="fav'+o.menuid+'" ref="'+o.menuid+'" src="yhui/images/menu/unstar.png" align="right" rel="'+ o.menuname +'" title="收藏->'+o.menuname+'"></div> ';
        		}
        	}

			if(o.child && o.child.length>0)
			{
				//li.find('div').addClass('icon-arrow');

				menulist += '<ul class="third_ul">';
				$.each(o.child,function(k,p){
					if (p.menuname =='-'){
						menulist += '<div class="menu-sep"></div>';
					}else{
						if(p.favflag=='1'){//如果标志1已收藏
							menulist += '<li><div><a ref="'+p.menuid+'" href="#" rel="' + p.url + '" ><img align="baseline" src="'+p.icon+'"><span class="nav">' + p.menuname + '</span></a> <img class="fav" type="removefav" id="fav'+p.menuid+'" ref="'+p.menuid+'" src="yhui/images/menu/star.png" align="right" rel="'+ p.menuname +'" title="取消收藏->'+p.menuname+'"></div> </li>';
						}else{
							menulist += '<li><div><a ref="'+p.menuid+'" href="#" rel="' + p.url + '" ><img align="baseline" src="'+p.icon+'"><span class="nav">' + p.menuname + '</span></a> <img class="fav" type="addfav" id="fav'+p.menuid+'" ref="'+p.menuid+'" src="yhui/images/menu/unstar.png" align="right" rel="'+ p.menuname +'" title="收藏->'+p.menuname+'"></div> </li>';
						}
						
					}				
					
					
				});
				menulist += '</ul>';
			}

			menulist+='</li>';
        })
		menulist += '</ul>';

		$('#nav').accordion('add', {
            title: n.menuname,
            content: menulist,
				border:false,
            iconCls: 'icon ' + n.icon
        });

		if(i==0)
			selectedPanelname =n.menuname;

    });
	$('#nav').accordion('select',selectedPanelname);

	//添加快捷菜单
    $('.fav').click(function(){
        var menuid   = $(this).attr("ref");
        var menuname = $(this).attr("rel");
        var type     = $(this).attr("type");
    	
    	if (type == "addfav"){
    		addfav(menuid,menuname);
    	}else{
    		removefav(menuid,menuname)
    	}
    	InitShortCut();
    	
    });
    //==========================================================
      
    
    //左侧菜单点击事件===============================================
	$('.navlist li a').click(function(){
		var tabTitle = $(this).children('.nav').text();

		var url = $(this).attr("rel");
		var menuid = $(this).attr("ref");
		var icon = $(this).find('.icon').attr('class');

		var third = find(menuid);
		if(third && third.child && third.child.length>0)
		{
			$('.third_ul').slideUp();

			var ul =$(this).parent().next();
			if(ul.is(":hidden"))
				ul.slideDown();
			else
				ul.slideUp();
		}
		else{
			addTab(tabTitle,url,icon);
			$('.navlist li div').removeClass("selected");
			$(this).parent().addClass("selected");
		}
	}).hover(function(){
		$(this).parent().addClass("hover");
	},function(){
		$(this).parent().removeClass("hover");
	});
	//=============================================================
	
	
	//选中第一个
	//var panels = $('#nav').accordion('panels');
	//var t = panels[0].panel('options').title;
    //$('#nav').accordion('select', t);
}
//获取左侧导航的图标
function getIcon(menuid){
	var icon = 'icon ';
	$.each(_menus.menus, function(i, n) {
		 $.each(n.menus, function(j, o) {
		 	if(o.menuid==menuid){
				icon += o.icon;
			}
		 })
	})

	return icon;
}

function find(menuid){
	var obj=null;
	$.each(_menus.menus, function(i, n) {
		 $.each(n.menus, function(j, o) {
		 	if(o.menuid==menuid){
				obj = o;
			}
		 });
	});

	return obj;
}

function addTab(subtitle,url,icon){
	if(!$('#main_tabs').tabs('exists',subtitle)){
		$('#main_tabs').tabs('add',{
			title:subtitle,
			content:createFrame(url),
			closable:true,
			icon:icon
		});
	}else{
		$('#main_tabs').tabs('select',subtitle);
		$('#mm-tabupdate').click();
	}
	tabClose();
}

function createFrame(url)
{
	var s = '<iframe scrolling="auto" frameborder="0"  src="'+url+'" style="width:100%;height:100%;"></iframe>';
	return s;
}

function tabClose()
{
	/*双击关闭TAB选项卡*/
	$(".tabs-inner").dblclick(function(){
		var subtitle = $(this).children(".tabs-closable").text();
		$('#main_tabs').tabs('close',subtitle);
	})
	/*为选项卡绑定右键*/
	$(".tabs-inner").bind('contextmenu',function(e){
		$('#tabmenu').menu('show', {
			left: e.pageX,
			top: e.pageY
		});

		var subtitle =$(this).children(".tabs-closable").text();

		$('#tabmenu').data("currtab",subtitle);
		$('#main_tabs').tabs('select',subtitle);
		return false;
	});
}


//绑定右键菜单事件
function tabCloseEven() {

    $('#tabmenu').menu({
        onClick: function (item) {
            closeTab(item.id);
        }
    });

    return false;
}

function closeTab(action)
{
    var alltabs = $('#main_tabs').tabs('tabs');
    var currentTab =$('#main_tabs').tabs('getSelected');
	var allTabtitle = [];
	$.each(alltabs,function(i,n){
		allTabtitle.push($(n).panel('options').title);
	})


    switch (action) {
        case "refresh":
            var iframe = $(currentTab.panel('options').content);
            var src = iframe.attr('src');
            $('#main_tabs').tabs('update', {
                tab: currentTab,
                options: {
                    content: createFrame(src)
                }
            })
            break;
        case "close":
            var currtab_title = currentTab.panel('options').title;
            $('#main_tabs').tabs('close', currtab_title);
            break;
        case "closeall":
            $.each(allTabtitle, function (i, n) {
                if (n != onlyOpenTitle){
                    $('#main_tabs').tabs('close', n);
				}
            });
            break;
        case "closeother":
            var currtab_title = currentTab.panel('options').title;
            $.each(allTabtitle, function (i, n) {
                if (n != currtab_title && n != onlyOpenTitle)
				{
                    $('#main_tabs').tabs('close', n);
				}
            });
            break;
        case "closeright":
            var tabIndex = $('#main_tabs').tabs('getTabIndex', currentTab);

            if (tabIndex == alltabs.length - 1){
            	$.messager.alert('','亲，后边没有啦 ^@^!!');
                return false;
            }
            $.each(allTabtitle, function (i, n) {
                if (i > tabIndex) {
                    if (n != onlyOpenTitle){
                        $('#main_tabs').tabs('close', n);
					}
                }
            });

            break;
        case "closeleft":
            var tabIndex = $('#main_tabs').tabs('getTabIndex', currentTab);
            if (tabIndex == 1) {
            	showWarning('','亲，前边那个上头有人，咱惹不起哦。 ^@^!!');
                return false;
            }
            $.each(allTabtitle, function (i, n) {
                if (i < tabIndex) {
                    if (n != onlyOpenTitle){
                        $('#main_tabs').tabs('close', n);
					}
                }
            });

            break;
        case "exit":
            $('#tabmenu').menu('hide');
            break;
    }
}


/*
 * 
 *getUserShortCut返回JSON格式：
 * 
 */
//初始化左侧
function InitShortCut() {
	$("#cutmenu").empty();
	var icount=0;    
    $.ajax({
        type: "GET",
        url : "getUserShortCut",
        data: '',
        dataType: 'json',
        async: false,
        success:function(reponse){
        	_shortcutmenus = reponse;
        },
        error: function(xhr, type){
        	showError('获取快捷菜单出错',"网络异常,无法获取用户快捷菜单");
        }
    });
    if (_shortcutmenus.menus ==" ") {
    	return;
    }
    $.each(_shortcutmenus.menus, function(i, n) {
		var cutlist ='';
		if (icount > 10) return;
		cutlist += '<a ref="'+n.menuid+'" href="#" rel="'+ n.url+'">';
        cutlist += '<img src="yhui/images/top_shortcut_menu.png">'; 
        cutlist += '<span class="nav" style="position: relative;top: -3px;color: #ffffff">'+n.menuname+'&nbsp&nbsp</span>';    
        cutlist += '</a>'
        $("#cutmenu").append(cutlist);
        icount++;
    });


	//=============================================================
	
	//为快捷菜单点击响应
	$('.cutlist a').click(function(){
		var tabTitle = $(this).children('.nav').text();

		var url = $(this).attr("rel");
		var menuid = $(this).attr("ref");
		var icon = $(this).find('.icon').attr('class');
		addTab(tabTitle,url,icon);
	});
    //===============================================================
}

function removefav(menuid,menuname){
	
	var params = "menuid=" + escape(menuid);

	$.ajax({
        type: "POST",
        url : "deleteUserShortCut",
        data: params,
        async: false,
        success:function(reponse){
            if (reponse.code == 0){
            	
            	$("#fav"+menuid).attr("type","addfav");
            	$("#fav"+menuid).attr("title","收藏->" + menuname);
            	$("#fav"+menuid).attr("src","yhui/images/menu/unstar.png");
//            	$.messager.alert('取消快捷菜单',"取消快捷菜单成功",'info');
            }
            else
              showError('取消快捷菜单',"取消快捷菜单失败:" + reponse.message);	
        },
        error: function(xhr, type){
        	showError('取消快捷菜单',"网络异常,无法取消快捷菜单");
        }
    });

}

function addfav(menuid,menuname){
	var params = "menuid=" + escape(menuid);
	
	$.ajax({
        type: "POST",
        url : "addUserShortCut",
        data: params,
        async: false,
        success:function(reponse){
            if (reponse.code == 0){
            	$("#fav"+menuid).attr("type","removefav");
            	$("#fav"+menuid).attr("title","取消收藏->" + menuname);
            	$("#fav"+menuid).attr("src","yhui/images/menu/star.png");
            }
            else
              showError('添加快捷菜单',"添加快捷菜单失败:" + reponse.message);	
        },
        error: function(xhr, type){
        	showError('添加快捷菜单',"网络异常,无法添加快捷菜单");
        }
    });
	
}


//=====系统上锁============================
function lockSystem(){
	
	var userid = getCurrentUserID();
	if (userid=='') return;
	
	$("#idx_username").textbox('setValue',userid);  //设置输入框的值
	$('#lockwindow').window('open');
	$("#idx_password").textbox('textbox').focus();
	$.cookie('ipoms_lock', 'true', { expires: 1 }); //设置cookie
	//响应回车事件
    $("#idx_password").textbox('textbox').keydown(function(e){
        if(e.keyCode==13){
        	unLockSystem();
        }
    });
}

//====系统解锁==============================
function unLockSystem(){
	
	var username = $("#idx_username").val();
    var password = $("#idx_password").val();
    var params = "username=" + escape(username) + "&password=" +escape(password)
    if (username == "" || password == "") {//check if the input is legal
    	showWarning("登录异常提示","账号和密码不可以为空!",function(){
    		$("#idx_password").textbox('textbox').focus();
    	});
    }else{
        $.ajax( {
            type : "POST",
            url : "loginCheck",
            data : params,
            async: false,
            success : function(msgJson) {
                var data = eval('(' + msgJson + ')');
                if( data.backstatus  == 'success'){
                	$.cookie('ipoms_lock',null);
                	$('#lockwindow').window('close');
                }else{
                	
                	showError("登录异常提示","Error:" + data.errormsg,function(){
                		$("#idx_password").textbox('textbox').focus();
                	});
                }
                	
            },
            error:function(data){
            	data = data['responseText'];
            	showError('登录异常提示',"网络异常,登录出错" + data,function(){
            		$("#idx_password").textbox('textbox').focus();
            	});
            }
        });
    }
}

//获取当前登录用户名
function getCurrentUserID(){
	
	var userid = '';
	$.ajax({
        type: "POST",
        url : "getCurrentUserID",
        data: '',
        async: false,
        success:function(reponse){
            if (reponse.code == 0){
              userid = reponse.data.userid;
            }
            else
            	showError('获取当前用户',"获取当前用户失败:" + reponse.message);	
        },
        error: function(xhr, type){
            ('获取当前用户',"网络异常,无法获取当前用户ID");
        }
    });
	return userid;
}


function showChangePasForm(){
	
	$('#changPassWindow').window('open');
	$("#old_password").textbox('textbox').focus();
	
}

$.extend($.fn.validatebox.defaults.rules, {
	/*必须和某个字段相等*/
	equalTo: {
	  validator:function(value,param){
	    return $(param[0]).val() == value;
	  },
	message:'字段不匹配'
	}

});



